package com.helen.ui.login;

import android.content.Intent;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.coorchice.library.SuperTextView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.helen.db.UserHelper;
import com.helen.entity.LoginRegisterEntity;
import com.helen.global.Constants;
import com.helen.shopping.R;
import com.helen.ui.BaseActivity;
import com.helen.ui.MainActivity;
import com.helen.utils.ActivityHelper;
import com.helen.utils.MD5;
import com.helen.utils.MyLog;
import com.helen.utils.PhoneUtils;
import com.helen.utils.tiputils.MToast;
import com.helen.widget.MyEditText;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by yang on 2018/4/14.
 * 注册
 */

public class RegisterActivity extends BaseActivity {
    @BindView(R.id.et_phone)
    MyEditText etPhone;
    @BindView(R.id.et_password)
    MyEditText etPassword;
    @BindView(R.id.et_sms_code)
    MyEditText etSmsCode;
    @BindView(R.id.tv_get_sms_code)
    TextView tvGetSmsCode;
    @BindView(R.id.et_recommend_phone)
    MyEditText etRecommendPhone;
    @BindView(R.id.tv_register)
    SuperTextView tvRegister;
    @BindView(R.id.tv_forget_password)
    TextView tvForgetPassword;
    @BindView(R.id.tv_login)
    TextView tvLogin;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_register;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.register);
    }

    @Override
    protected void updateViews() {

    }


    @OnClick({R.id.tv_get_sms_code, R.id.tv_register, R.id.tv_forget_password, R.id.tv_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_get_sms_code:
                String phoneCode = etPhone.getText().toString().trim();
                if (TextUtils.isEmpty(phoneCode)) {
                    MToast.makeTextShort(RegisterActivity.this, "手机号不能为空").show();
                    etPhone.requestFocus();
                    return;
                }

                if (!PhoneUtils.isMobileNO(phoneCode)) {
                    MToast.makeTextShort(RegisterActivity.this, "手机号格式错误").show();
                    etPhone.requestFocus();
                    return;
                }
                getMsgCodeApi(phoneCode);
                break;
            case R.id.tv_register:
                String phone = etPhone.getText().toString().trim();
                String code = etSmsCode.getText().toString().trim();
                String pwd = etPassword.getText().toString().trim();
                String rePhone = etRecommendPhone.getText().toString().trim();
                if (TextUtils.isEmpty(phone)) {
                    MToast.makeTextShort(RegisterActivity.this, "手机号不能为空").show();
                    etPhone.requestFocus();
                    return;
                }

                if (!PhoneUtils.isMobileNO(phone)) {
                    MToast.makeTextShort(RegisterActivity.this, "手机号格式错误").show();
                    etPhone.requestFocus();
                    return;
                }

                if (TextUtils.isEmpty(pwd)) {
                    MToast.makeTextShort(RegisterActivity.this, "密码不能为空").show();
                    etPassword.requestFocus();
                    return;
                }

                if (TextUtils.isEmpty(code)) {
                    MToast.makeTextShort(RegisterActivity.this, "验证码不能为空").show();
                    etSmsCode.requestFocus();
                    return;
                }

                registerApi(phone, code, pwd, rePhone);
                break;
            case R.id.tv_forget_password:
                startActivity(new Intent(RegisterActivity.this, FindPasswordActivity.class));
                break;
            case R.id.tv_login:
                finish();
                break;
        }
    }


    //注册接口
    private void registerApi(final String phone, String code, final String pwd, String rePhone) {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("type", "2");
        params.put("id", "");
        params.put("name", "");
        params.put("img", "");
        params.put("phone", phone);
        params.put("code", code);
        params.put("pwd", pwd);
        params.put("rePhone", rePhone);
        EasyHttp.post(Constants.API_JSONAPI_REGISTER)
                .params(params)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.d(TAG, "注册失败==" + e.toString());
                        MToast.makeTextShort(RegisterActivity.this, getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String result) {
                        String data = PhoneUtils.checkResponseFlag(RegisterActivity.this, result, TAG);
                        if (data != null) {
                            Gson gson = new GsonBuilder().create();
                            LoginRegisterEntity registerEntity = gson.fromJson(data, LoginRegisterEntity.class);
                            MyLog.d("yang","1id="+registerEntity.getId());
                            UserHelper.getInstance().saveUserAuth(phone, pwd, true);
                            UserHelper.getInstance().saveUserInfo(RegisterActivity.this, data);
                            UserHelper.getInstance().setIsLogined(true);
                            startActivity(new Intent(RegisterActivity.this, MainActivity.class));
                            ActivityHelper.getInstance().finishAllActivity();
                        }


                    }
                });
    }


    //    获取验证码接口
    private void getMsgCodeApi(String phone) {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("id", phone);
        params.put("key", MD5.getMD5Str(phone + "888888").toUpperCase());
        EasyHttp.post(Constants.API_JSONAPI_SMS_CODE)
                .params(params)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.d(TAG, "获取验证码失败==" + e.toString());
                        MToast.makeTextShort(RegisterActivity.this, getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String result) {
                        String data = PhoneUtils.checkResponseFlag(RegisterActivity.this,result,TAG);
                        if(data!=null){
                            timer.start();
                        }
                    }
                });
    }

    //   倒计时响应事件  timer.start();
    private CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            tvGetSmsCode.setClickable(false);// 设置不能点击
            tvGetSmsCode.setText(millisUntilFinished / 1000 + "秒后重新发送");// 设置倒计时时间
            tvGetSmsCode.setTextColor(getResources().getColor(R.color.appTipColor)); // 设置为灰色，这时是不能点击的
        }

        @Override
        public void onFinish() {
            tvGetSmsCode.setText(getResources().getString(R.string.get_sms_code));
            tvGetSmsCode.setClickable(true);// 重新获得点击
            tvGetSmsCode.setTextColor(getResources().getColor(R.color.appThemeColor));

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }
}
